import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder, ValidatorFn } from '@angular/forms';
import { OptionItem, MessageService, ModalService } from '@iux/live';

@Component({
  templateUrl: './with-drawer.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class WithDrawerComponent implements OnInit {
  constructor(private fb: FormBuilder, private message: MessageService, private modalService: ModalService) { }
  formGroup: FormGroup;
  contactData: OptionItem[];
  genderData: OptionItem[];
  @ViewChild('drawerContent', { static: false }) drawerContent;
  @ViewChild('form', { static: false }) form;

  ngOnInit() {
    this.contactData = this.initData();
    this.genderData = this.initGenderData();
    this.initForm();
  }

  openDrawer() {
    this.modalService.create({
      lvModalKey: `my_drawer_right`,
      lvType: 'drawer',
      lvWidth: 'M',
      lvOuterClosable: true,
      lvCloseButtonDisplay: true,
      lvDrawerPositionOffset: ['0px', '0px', '0px', '0px'],
      lvHeader: 'Modal Title',
      lvContent: this.drawerContent,
      lvOk: () => {
        for (const key of Object.keys(this.formGroup.controls)) {
          this.formGroup.controls[key].markAsDirty();
          this.formGroup.controls[key].updateValueAndValidity();
        }
        if (this.formGroup.invalid) {
          setTimeout(() => {
            // 找到第一个error的元素，调用原生的scrollIntoView，实现提交失败自动滚动到第一个错误字段
            const errorEle = (Array.from(this.form.elementRef.nativeElement.children) as HTMLElement[]).find(item => item.querySelector('.lv-form-control-has-error'))
            errorEle.scrollIntoView();
          })
          return false;
        } else {
          this.message.success('Next...');
        }
      }
    });
  }

  initData() {
    return [
      {
        label: 'email',
        isLeaf: true
      },
      {
        label: 'phone',
        isLeaf: true
      }
    ];
  }

  initGenderData() {
    return [
      {
        label: 'male',
        isLeaf: true
      },
      {
        label: 'female',
        isLeaf: true
      }
    ];
  }

  initForm() {
    this.formGroup = this.fb.group({
      name: ['', [Validators.required, this.validName()]],
      nickname: [''],
      age: ['', Validators.required],
      password: ['', Validators.required],
      gender: ['', Validators.required],
      contact: ['email'],
      website: [''],
      description: [''],
      note: [''],
    });
    this.onContactChange('email');
  }

  // 自定义校验
  validName(): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => control.value !== 'abcd' ? null : { nameExist: true };
  }

  onContactChange(value) {
    if (value === 'email') {
      const ctrl = new FormControl('', [Validators.maxLength(10)]);
      this.formGroup.addControl('email', ctrl);
      this.formGroup.removeControl('phone');
    } else if (value === 'phone') {
      const ctrl = new FormControl('', [Validators.maxLength(10)]);
      this.formGroup.addControl('phone', ctrl);
      this.formGroup.removeControl('email');
    }
  }
}
